/*
 * @copyright: Huang Ding
 * @Author: ding-cx
 * @Date: 2020-12-01 14:08:35
 * @LastEditors: ding-cx
 * @LastEditTime: 2021-03-20 10:33:19
 * @Description: file content
 */

import {
  getStore,
  setStore
} from "@/utils/storage"

import {
  asyncRoutes,
  constantRoutes,
  dbRoutes,
} from '@/router'

import {
  svs_permission
} from "@/api/user"
// import bacc from "@/service/sys/menus"
// console.log(bacc);

/**
 * TODO  改造这个权限的设计。不是每个路由属于固定的某几个role。而是具有权限名称即可。
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
  const res = []

  routes.forEach(route => {
    const tmp = {
      ...route
    }
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })

  return res
}


const state = {
  routes: [],
  addRoutes: [],
  custom_perm_list: [], //自定义权限标识表
  common_perm_list: [], //通用权限id表
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  },
  SET_PERMISSION(state, perm_list) {
    state.custom_perm_list = perm_list.custom_perm; //数组。
    state.common_perm_list = perm_list.common_perm; //对象，menu_id:[1,2]。
    // 不能将权限存在store或cookie中，太不安全。
    // setStore('custom_perm_list', state.custom_perm_list);
    // setStore('common_perm_list', state.common_perm_list);
    // Cookies.set('custom_perm_list', state.custom_perm_list.join(","))
  }
}

const actions = {
  /** 生成动态路由 */
  generateRoutes({
    commit
  }) {
    return new Promise(resolve => {
      // let accessedRoutes = []

      dbRoutes().then(dbRoute => {
        // console.log(dbRoute);
        // accessedRoutes.unshift(...dbRoute)
        //加个兜底的路由，捕获到均转至404 
        const asyncRoute = dbRoute.concat({
          path: "*",
          redirect: "/404",
          name: "404",
          hidden: true,
        })
        commit('SET_ROUTES', asyncRoute)
        resolve(asyncRoute)
      })
    })
  },
  /** 获取登录用户的权限表 */
  getLoginedUserPermList({
    commit
  }) {
    svs_permission().then(res => {
      // console.log(res);
      commit("SET_PERMISSION", res)
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
